package com.ibm.spatiotemp.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;

import com.ibm.spatiotemp.server.datasources.DataSchema;
import com.ibm.spatiotemp.server.datasources.DataSource;
import com.ibm.spatiotemp.tools.Constants;

public class ConnectionManager {
	
	private String driver = "com.informix.jdbc.IfxDriver";
	private String url = null;
	private DataSchema dataschema = null;
	
	public ConnectionManager(DataSource ds) throws SQLException {
		this.url = ds.getConnection_string();
		this.dataschema = ds.getDataschema();	    
	}

	public Connection newConnection() throws SQLException {
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			throw new SQLException("Can't find class for driver: " + driver);
		}
		Connection newConn = null;
		newConn = DriverManager.getConnection(url);
		newConn.setAutoCommit(true);
		Statement st = newConn.createStatement();
		st.execute("set lock mode to wait 30;set isolation to dirty read;set pdqpriority 90;");
		st.close();
		return newConn;
	}

	public void close() {	   
	}
	
	public DataSchema getDataschema() {
		return dataschema;
	}
	
	public HashSet<String> initIDSet(Connection conn) throws SQLException {
		HashSet<String> idSet = new HashSet<String>();
		Statement st = conn.createStatement();
		String format = "select %s from %s";
		String sqlString = String.format(format, dataschema.getMovobj_colname(), Constants.TABLE_NAME);
		ResultSet resultSet = st.executeQuery(sqlString);
		while (resultSet.next()) {
			String modid = resultSet.getString(1);
			idSet.add(modid);
		}	
		resultSet.close();
		st.close();
		return idSet;
	}
	
	public void initPrimaryKey(Connection conn, String id) throws SQLException {
		Statement st = conn.createStatement();
		String format = "insert into %s(%s, %s) values (\'%s\', %s)";
		String sqlString = String.format(format, Constants.TABLE_NAME, dataschema.getMovobj_colname(), Constants.TSCOLUMN_NAME,	id, dataschema.getOther());
		st.executeUpdate(sqlString);
		st.close();		
	}
	
}


